var mysql = require('mysql');
var connection;
function handleDisconnect() {
    connection = null;
    connection = mysql.createConnection({
        host: '112.74.192.62',
        user: 'swyin',
        password: '357844730',
        database: 'kingdombug',
        port: '3306'
    });
    connection.connect(function (err) {
        if (err) {
            console.log('error when connecting to db:', err);
            setTimeout(handleDisconnect, 2000);
        }
        else
            console.log("DATABASE IS LISTENING PORT:3306");
    });
    connection.on('error', function (err) {
        if (err.code === 'PROTOCOL_CONNECTION_LOST') {
            handleDisconnect();
        } else {
            throw err;
        }
    });
}
handleDisconnect();
var express = require('express');
var app = express();
var server = require('http').createServer(app);
app.use('/', express.static(__dirname));
server.listen(process.env.PORT || 80);
console.log("SERVER IS LISTENING PORT:80");
var ws = require('ws').Server;
var server = new ws({port: 1947});
var handleProtocol = require("./protocol");
console.log("WEBSOCKET IS LISTENING PORT:1947");
var socketList = [];
server.on('connection', function (socket) {
    socketList.push(socket);
    console.log('CONNECTING SOCKET NUM:' + socketList.length);
    var isSent = false;
    var heartbeat = setInterval(sendHeartbeat, 60000);
    socket.on('message', function (message) {
        if (message == 'heartbeat') {
            isSent = false;
        }
        else {
            var clientInfo = JSON.parse(message);
            handleProtocol.handleProtocol(connection, socket, clientInfo);
        }
    });
    function sendHeartbeat() {
        if (isSent == false && socket.readyState == 1) {
            socket.send('heartbeat');
            isSent = true;
        }
        else {
            clearInterval(heartbeat);
            socketList.splice(socket, 1);
            socket.close();
            socket = null;
            console.log('CONNECTING SOCKET NUM:' + socketList.length);
        }
    }
});


var itemsData = [{id: 10000, type: 1, num: 1}, {id: 10001, type: 2, num: 1}, {id: 10002, type: 3, num: 1}];
var itemsJson = JSON.stringify(itemsData);
var update = 'update table backpack set items=';